/*
 * @Author: hongjianfeng
 * @Date: 2023-07-31 11:22:43
 * @LastEditTime: 2023-08-15 13:51:38
 * @Description: 
 * @FilePath: \info\web\detail.js
 */
// document.addEventListener('UniAppJSBridgeReady', function() {
//   uni.getEnv(function(res) {
//     console.log('当前环境：' + JSON.stringify(res));
//   });
//   console.log(111,uni);
  
// })


var vm = new Vue({
  el: '#unity-app',
  components: { 
    // nbVoiceRecord
  },
  data: {
    baseUrl : 'http://8.141.90.108:8084/portal',
    APIThird : 'http://8.141.90.108:8084/third',
    showPage:false,
    qType: null,// 类型id，上个页面带
    queIndex:0,
    groupIndex:0,
    // 类型对应体制
    typeList:[
      {
        type: 1,
        name: '阳虚质'
      },
      {
        type: 2,
        name: '阴虚质'
      },
      {
        type: 3,
        name: '气虚质'
      },
      {
        type: 4,
        name: '痰湿质'
      },
      {
        type: 5,
        name: '湿热质'
      },
      {
        type: 6,
        name: '血瘀质'
      },
      {
        type: 7,
        name: '特禀质'
      },
      {
        type: 8,
        name: '气郁质'
      },
      {
        type: 9,
        name: '平和质'
      }
    ],
    // 问卷主体列表
    queList:[],
    txtList:[],
    titleTop:'AI医师推荐',
    btnTxt:'开始问诊',
    id:'',
    cj:'',// 1,2,3,4,5
    recording: true, // 录音中
		recordPopupShow: false,// 录音弹窗
    avatar:'',
    areaTxt:'',
    isMod:true,
    isCheck:false,
    mp3Url:'',
    params: null
  },
  watch: {
    mp3Url(n){
      console.log(22122,this.showPage);
      if(this.showPage){
        this.playMp3()
      }
    },
    showPage(){
      console.log('pageshowWatch');
      this.playMp3()
    }
		// loca(n) {
		// 	alert(JSON.stringify(n));
		
		// }
	},
  created(){
      
  },
  mounted(){
    this.init()
  },
  destroyed:function(){
    console.log('实例销毁之后调用')
  },
  methods: {
    init(){
      // 方法暴露给录音使用
      window.recoderStartCallBack = this.recoderStartCallBack
      window.recoderMoveCallBack = this.recoderMoveCallBack
      window.recoderEndCallBack = this.recoderEndCallBack
      
      this.params = this.getUrlParam()
      // alert(JSON.stringify(this.params));
      console.log('params:',this.params);
      
      let {cj,token} = this.params

      // alert(JSON.stringify(this.params?.word))
      try{
        if(this.params.avatar){
          this.avatar = this.params.avatar
        }
      }catch(e){}
      try{
        if(this.params.word){
          this.areaTxt = decodeURIComponent(this.params.word)
        }
      }catch(e){}
      let title = ''
      this.cj = Number(cj)
      if(cj == 1 || cj == 5){
        title = 'AI医师问诊'
        this.titleTop = 'AI医师推荐'
        this.btnTxt = '开始问诊'
        this.mp3Url = '/show/question/doctorIntro.mp3'
        // this.playMp3(this.mp3Url)
      }
      if(cj == 2){
        title = '症状问询'
        this.titleTop = 'AI医师推荐'
        this.btnTxt = '按住说话'
      }
      if(cj == 3){
        title = 'AI医师问诊'
        this.titleTop = '问诊医师（张医师）'
        this.btnTxt = '开始辩证'
        this.isCheck = this.params?.isCheck
        this.wordToVoice()
        // this.mp3Url = '/show/question/doctorIntro.mp3'
        // this.playMp3(this.mp3Url)
      }
      // console.log(2222,cj);
      if(cj == 4){
        title = '体质问答（1/4）'
        this.titleTop = ''
        this.btnTxt = '按住说话'
        
        let {id,qType,doctorSex} = this.params
        this.id = id
        this.doctorSex = doctorSex
        if(qType){
          // 上一次所做题目type（题目提交按type一组一组提交），这次进来后要遍历到该id的下一道题
          this.groupIndex = Number(qType)
        }
        // console.log(11111);
        this.getQuaList()
      }
      // mp3Url = 'http://139.198.18.134:8084/portal/show/question/doctorIntro.mp3'
      
      
      // this.timer = setTimeout(()=>{
        uni.postMessage({
          data: {
              action: 'message'
          }
        });
      // },2000)
      document.title = title
    },
    /**
     * @description: 文字转语音
     * @event: 
     * @return {*}
     */    
    wordToVoice(){
      let _th = this
      axios({
        method: 'get',
        url: this.APIThird+'/tencent/cloud/wordToVoice?word=' + _th.areaTxt,
        headers: {
          'Authorization':'Bearer '+ _th.params.token,
          'content-type': 'application/json'
        }
      }).then(function (res) {
        if(res.data.code === 200){
          // alert(JSON.stringify(res))
          // let list = res.data.data
          if(res.data.data.indexOf('null') === -1){
            _th.mp3Url = res.data.data
          }
          
        }else{
          _th.Toast(res.data.message)
        }
        

      }).catch(function (error) {
        // alert('error:')
        _th.Toast(error)
          console.log('error:',error);
      });

      
    },
    /**
     * @description: 语音播放
     * @event: 
     * @return {*}
     */
    async playMp3(){
      try{
        console.log('playmp3:',this.baseUrl + this.mp3Url);
        // myGameInstance.SendMessage("Main Camera", "audioStop");
        
        if(this.mp3Url.indexOf('doctorIntro.mp3') != -1){
          myGameInstance.SendMessage("Main Camera", "ddaudioPlay", "555");
        }else{
          myGameInstance.SendMessage("Main Camera", "audioPlay", this.baseUrl + this.mp3Url);
        }
        // myGameInstance.SendMessage("Main Camera", "audioPlay", 'http://8.141.90.108:8084/portal/show/question/question29m.mp3');
        // myGameInstance.SendMessage("Main Camera", "audioPlay", 'http://8.141.90.108:8084/portal/show/question/doctorIntro.mp3');
        return
        if(myGameInstance?.SendMessage && this.mp3Url && this.showPage){
          this.timer = setTimeout(()=>{
            console.log('playmp3:',this.baseUrl + this.mp3Url);
            alert('playmp3')
            myGameInstance.SendMessage("Main Camera", "audioPlay", 'http://8.141.90.108:8084/portal/show/question/question29m.mp3');
            // myGameInstance.SendMessage("Main Camera", "audioPlay", this.baseUrl + this.mp3Url);
          },10000)
        }
      }catch(e){}
      
    },
    
    // 录音开始调用方法
    recoderStartCallBack(v){
      this.recording =  true // 录音中
      this.recordPopupShow = true// 录音弹窗
    },
    // 录音开始调用方法
    recoderMoveCallBack(moveY){
      if (moveY < -50) {
        this.recording = false;
      } else {
        this.recording = true;
      }
    },
    // 录音结束后调用方法
    recoderEndCallBack(filePath){
      let _th = this
      this.timer = setTimeout(()=>{
        this.recording =  false // 录音中
      },220)
      this.recordPopupShow =  false// 录音弹窗
      axios({
        method: 'post',
        url: APIThird+'/tencent/cloud/voiceToWord?language=' + Number(_th.params.language),
        headers: {
          'Authorization':'Bearer '+ _th.params.token,
          "Content-Type": "multipart/form-data",
        },
        data: {
          filePath
        }
      }).then(function (res) {
        alert(JSON.stringify(res))
        if(res.data.code === 200){
          _th.handleTranslate(res.data.word.split(''))
        }else{
          _th.Toast(res.data.message)
        }
      }).catch(function (error) {
        alert('error:')
          console.log('error:',error);
      });
    },
    getQuaList(){
      let _th = this
      axios({
        method: 'get',
        url: this.baseUrl+'/aims/question/getPhysiqueQuestionList',
        headers: {
          'Authorization':'Bearer '+ _th.params.token,
          'content-type': 'application/json',
        },
        data: {
          doctorSex: _th.doctorSex
        }
      }).then(function (res) {
        // alert(JSON.stringify(res))
        if(res.data.code === 200){
            let list = res.data.data
      // console.log(222,list);
            let arr = []
            list.forEach(item=>{
            // item.url = 'http://192.168.1.5:8084/portal/show/11.mp3'
            item.ans = [ //问卷答案
              {
                  score: 1,
                  label:'A.没有'
              },
              {
                  score: 2,
                  label:'B.很少'
              },
              {
                  score: 3,
                  label:'C.有时'
              },
              {
                  score: 4,
                  label:'D.经常'
              },
              {
                  score: 5,
                  label:'E.总是'
              }
            ]
            _th.typeList.forEach((titem, tindex)=>{
              if(titem.type === item.type){
                item.typeName = titem.name
                arr[tindex]?.length ? '' : (arr[tindex] = [])
                arr[tindex].push(item)
              }
            })
          })
          console.log(arr);
          
          _th.queList = arr
          _th.nextQue()
        }else{
          _th.Toast(res.data.message)
        }
      }).catch(function (error) {
        // alert('error:')
         _th.Toast(error)
          console.log('error:',error);
      });
      
    },
    // 赋值底部滚动区域机器人文字
    nextQue(){
      let txtObj = this.queList[this.groupIndex][this.queIndex]
      this.txtList.push({
        type: 1,
        txt: `${txtObj.sort}.${txtObj.question}`
      })
      // 播放语音
      this.mp3Url = txtObj.url
      // this.playMp3(txtObj.url)
      this.autoScroll()
    },
    /**
     * @description: 翻译，A，没有。
     * @event: 
     * @param {*} arr
     * @return {*}
     */    
    handleTranslate(arr){
      // console.log(11,arr);
      this.queList[this.groupIndex][this.queIndex].ans.forEach(item1=>{
        // console.log(22,item1);
        //  || arr.includes(item1.label.split('')[2])
        if(arr.includes(item1.label.split('')[0])){
          this.handleQueClick(item1,()=>{
            this.timer = setTimeout(()=>{
              this.handleNext('next')
            },500)
          })
        }
      })
    },
    /**
     * @description: 答案点击
     * @event: 
     * @param {*} item
     * @param {*} list
     * @return {*}
     */    
    handleQueClick(item, cb){
      this.queList[this.groupIndex][this.queIndex].ans.forEach(item1=>{
        item1.act = false
      })
      item.act = true
      // 赋值底部滚动区域答案文字
      this.txtList.push({
        type: 2,
        txt: `${item.label}`
      })
      this.autoScroll()
      cb && cb()
    },
    // 聊天区域自动滚动到底部
    autoScroll() {
      let scroll_to_bottom = document.getElementById('chat-box');
      try{
		    scroll_to_bottom.scrollTop = scroll_to_bottom?.scrollHeight;
      }catch(e){

      }
      
    },
    /**
     * @description: 验证题目有没做完
     * @event: 
     * @return {*}
     */    
    checkQue() {
      let ans = this.queList[this.groupIndex][this.queIndex].ans
      let bo = true
      ans.forEach((item,index)=>{
        if(item.act){
          bo = false
        }
      })
      return bo
      
    },
    /**
     * @description: 
     * @event: 
     * @param {*} val : next 下一题  prev 上一题
     * @return {*}
     */    
    handleNext(val){
      let _th = this
      // console.log(111,val ,this.queIndex , this.queList.length );
      if(val === 'next'){
        // console.log(111,this.queIndex + 1 , this.queList[this.groupIndex].length);
        if(this.queIndex + 1  < this.queList[this.groupIndex].length){
          // 判断当前题目是否选中，没有不让进入下一题
          // let ans = this.queList[this.groupIndex][this.queIndex].ans
          // let bo = true
          // ans.forEach((item,index)=>{
          //   if(item.act){
          //     bo = false
          //   }
          // })
          if(this.checkQue()){
            this.Toast('请选择当前题目')
            return
          }
          this.queIndex += 1
          this.nextQue()
        }else{
          // console.log(333);
          // 提交题目
          if(this.groupIndex + 1  <= this.queList?.length){
            let list = []
            let type = ''
            this.queList[this.groupIndex].forEach(item=>{
              let obj = {
                medicalExaminationId: this.id,
                questionId: item.id,
                computeType: item.computeType
              }
              item.ans.forEach(item1=>{
                if(item1.act){
                  obj.answerScore = item1.score
                  obj.answerTitle = item1.label
                }
              })
              type = item.type
              list.push(obj)
            })
            // console.log(2222,list,type);
            // 
            if(this.checkQue()){
              this.Toast('请选择当前题目')
              return
            }

            axios({
              method: 'post',
              url: this.baseUrl+'/aims/answer/addExaminationAnswerBatch',
              headers: {
                'Authorization':'Bearer '+ _th.params.token,
                'content-type': 'application/json',
              },
              data: {
                list,
                type
              }
            }).then(function (res) {
              if(res.data.code === 200){
                // alert(JSON.stringify(res))
                let list = res.data.data
                _th.queIndex = 0
                _th.groupIndex +=1
                // console.log(333,this.groupIndex , this.queList.length);
                if(_th.groupIndex === _th.queList?.length){
                  uni.navigateTo({ url: '/pages/wit/examine/step/face?id=' + _th.id});
                }else{
                  _th.nextQue()
                }
              }else{
                _th.Toast(res.data.message)
              }
              
      
            }).catch(function (error) {
              // alert('error:')
              _th.Toast(error)
                console.log('error:',error);
            });
            return
          }
          // 判断题目组是不是最后一组，是的话跳转上传面部图片
          // uni.navigateTo({ url: '/pages/wit/examine/step/face' });
        }
      }else{
        if(this.queIndex > 0){
          this.queIndex -= 1
          this.nextQue()
        }
      }
    },
    handleMod(){
      let _th = this
      this.isMod = !this.isMod
      if(this.isMod){
        // addDiagnosis({
        //   keyWords: this.areaTxt
        // }).then(res => {
        //   if(res.code === 200){
        //     let id = this.id ? this.id : res.data.id
        //     uni.navigateTo({ url: '/pages/wit/examine/collect/discriminate?id='+id});
        //   }
        // })

        var promise = fetch(this.baseUrl+'/aims/diagnosis/addDiagnosis', {
          method: 'post',
          body: JSON.stringify({"keyWords":_th.areaTxt}),
          headers: {
            'Authorization':_th.params.token,
            'Content-Type': 'application/json'
          }
        })
       
        .then(function(response) {
         if(response.status === 200){
            return response.json();
          }else{
            return {}
          }
        })
        promise.then(function(data){
          //响应的内容
          console.log(data);
          
        }).catch(function(err){
          console.log(err);
        })
      }
    },
   
    handleResult(type){
      let _th = this
      let url = ``;
      if(type == 1){
        axios({
          method: 'post',
          url: this.baseUrl+'/aims/examination/addMedicalExamination',
          headers: {
            'Authorization':'Bearer '+ _th.params.token,
            'content-type': 'application/json'
          },
          data: {}
        }).then(function (res) {
          let res1 = res.data
          if(res1.code === 200){
            this.id = res1.data.id
            if(res1.data?.questionType){
              this.qType =  res1.data.questionType
            }
            if(res1.data?.modleType){
              // 跳转到脸部或者舌 1题目，2脸部，3舌
              this.modleType =  res1.data?.modleType
            }
            let par = this.id
            // 代表上一次还有没完成的题目
            if(this?.qType){
              par = par + '&qType=' + this.qType
            }
            if(this.modleType === 2){
              uni.navigateTo({ url: '/pages/wit/examine/step/face?id=' + this.id});
            }else if(this.modleType === 3){
              uni.navigateTo({ url: '/pages/wit/examine/step/tongue?id=' + this.id});
            }else{
              myGameInstance.SendMessage("Main Camera", "ddaudioStop", "555");
              uni.navigateTo({ url: '/pages/wit/examine/step/question?id=' + par});
            }
          }else{
            _th.Toast(res.data.message)
          }
  
        }).catch(function (error) {
          // alert('error:')
          _th.Toast(error)
            console.log('error:',error);
        });
        return
      }
      if(type == 5){
        myGameInstance.SendMessage("Main Camera", "ddaudioStop", "555");
        url = `/pages/wit/examine/collect/question`;
      }
      if(type == 3){
        url = '/pages/wit/examine/collect/discriminate?id='+ _th.id;
      }
      uni.navigateTo({
        url
      });
    },
    getUrlParam(key, uurl){
      if (uurl == null || uurl == ""){
       uurl = window.location.href;
      }
      var url = decodeURI(uurl);
      var paramMap = {};
      var firstIndex = url.indexOf("?");
      var paramStr = url.substring(firstIndex+1);
      if (paramStr && paramStr != "") {
        var index = paramStr.indexOf("?") //再次检查参数，避免后面有参数的值是访问地址
        var lastVal = "";
        var sflag = false; //标识有第二个问号
        if(index>0){
          var urlTemp = paramStr.substring(0, index);
          var lastIndex = urlTemp.lastIndexOf("=");
          lastVal = paramStr.substring(lastIndex+1);
          paramStr = paramStr.substring(0, lastIndex+1);
        }
        var paramStrArr = paramStr.split("&");
        for (var i = 0; i < paramStrArr.length; i++) {
          var temp = paramStrArr[i];
          var indexE = temp.indexOf("=");
          var pKey = temp.substring(0, indexE);
          var pVal = "";
          if(sflag && i==(paramStrArr.length-1)){
            pVal = lastVal;
          }else{
            pVal = temp.substring(indexE + 1);
          }
          paramMap[pKey] = pVal;
        }
      }
      return paramMap;
    },
    
    Toast(msg,duration){
      duration=isNaN(duration)?3000:duration;
      var m = document.createElement('div');
      m.innerHTML = msg;
      m.style.cssText="max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
      document.body.appendChild(m);
      setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
      }, duration);
    }
   
  }
})
